package com.github.wxpay.controller;

import com.github.wxpay.sdk.QGWxPayConfig;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@RestController
public class PayDemoController {

    @GetMapping("/api/getcodeurl")
    // 获取code_url,返回给前端
    public Map<String, String> getCodeUrl(String orderNo) throws Exception {
        QGWxPayConfig config = new QGWxPayConfig();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "腾讯充值中心-QQ会员充值");
        data.put("out_trade_no", "2020071310595900000014");
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", "1");
        data.put("spbill_create_ip", "127.0.0.1");
        data.put("notify_url", "http://3196160xk2.wicp.vip:13521/api/wxpay/cb");
        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
        data.put("product_id", "12");
        Map<String, String> resp = null;
        try {
            resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }


    // 微信支付的回调
    @PostMapping("/api/wxpay/cb")
    public void wxPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 从请求中获取发送过来的xml数据
        ServletInputStream inputStream = request.getInputStream();
        InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
        BufferedReader reader = new BufferedReader(inputReader);
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        System.out.println("回调接收到的数据:");
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            stringBuilder.append(line);
        }
        reader.close();
        inputReader.close();
        inputStream.close();
        // 把接收到的xml转换为map
        Map<String, String> requestMap = WXPayUtil.xmlToMap(stringBuilder.toString());
        QGWxPayConfig config = new QGWxPayConfig();
        WXPay wxpay = new WXPay(config);
        System.out.println("map结果:");
        System.out.println(requestMap);
        // 验证内容是否正确的
        Map<String, String> responseMap = new HashMap<>();
        //  if (wxpay.isPayResultNotifySignatureValid(requestMap)) {
        if (WXPayUtil.isSignatureValid(requestMap, config.getKey(), WXPayConstants.SignType.HMACSHA256)) {
            System.out.println("签名正确");
            // 签名正确
            // 进行处理。
            // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
            // 返回结果
            responseMap.put("return_code", "SUCCESS");
            responseMap.put("return_msg", "OK");
        } else {
            // 签名错误，如果数据里没有sign字段，也认为是签名错误
            System.out.println("签名错误");
            responseMap.put("return_code", "FAIL");
            responseMap.put("return_msg", "签名失败");
        }
        // 把map转为xml
        String responseXml = WXPayUtil.mapToXml(responseMap);
        response.getWriter().write(responseXml);
    }

    @GetMapping("/api/testhsk")
    public Map<String, String> testHsk() throws Exception {
        Map<String, String> responseMap = new HashMap<>();
        responseMap.put("msg", "sucess");
        return responseMap;
    }
}
